package com.example.finalcode;

import java.util.Scanner;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SecondActivity extends Activity {
	
	private Button btninput; 
	private EditText inputview;
	private TextView tvpoint;
	int answer;
	int count ;
	//int userInput;
	int lowerBound;
	int upperBound;
	//

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_second);
		
		
		initView();
		initHandler();
		
		
	}

	private void initHandler() {
		// TODO Auto-generated method stub
		//數入列上輸入數值後，按下Button,若答案與輸入數字相同則跳到下一頁
		
		//Scanner sc = new Scanner(System.in);
		btninput.setOnClickListener(new View.OnClickListener() {
		
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//userInput = this.sc.nextInt();
				count++;
				
						
				//s = inputview.getText().toString();
				
				
				Intent it = new Intent();
				it.setClass(SecondActivity.this, SecondActivity.class);
				
				Bundle bu = new Bundle();
				bu.putString("inputview", inputview.getText().toString());
				
				//it.putExtras(bu);
				//tvpoint.setText(bu.getString("inputview"));
				
				finalCode();
				
				
				//SecondActivity.this.startActivity(it);
				//SecondActivity.this.finish();
				
			}
		});
		
	}
	
	

	private void initView() {
		// TODO Auto-generated method stub
		btninput = (Button)findViewById(R.id.btn_input);
		inputview = (EditText)findViewById(R.id.inputText);
		tvpoint = (TextView)findViewById(R.id.point);
		answer = (int)(Math.random()*100)+1;
		count = 0;
		lowerBound = 1;
		upperBound = 100;
		
	}
	
	private void finalCode(){
		int i = Integer.valueOf(inputview.getText().toString());
		
		
		if(i == answer){
			//tvpoint.setText("Game over! COUNT = " + count + ", ANSWER =  " + answer);
			Intent intent = new Intent();
			intent.setClass(SecondActivity.this, ThirdActivity.class);
			startActivity(intent);
			
		}else{
				//比對失敗,調整上下邊界
				if(i < answer && i >= lowerBound){
					lowerBound  = i +1;
				tvpoint.setText("Please enter a number between "+lowerBound+" ~ "+upperBound);	
				}
				
				if(i > answer && i <= upperBound){
					upperBound  = i -1;
				tvpoint.setText("Please enter a number between "+lowerBound+" ~ "+upperBound);
				}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.second, menu);
		return true;
	}

}
